<template>
  <el-card class="sku-card">
    <el-form
      label-width="100px"
      :model="skuFormData"
      :rules="rules"
      ref="skuFormRef"
    >
      <el-form-item label="SPU名称">
        <span>{{ spu.spuName }}</span>
      </el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input
          placeholder="请输入SKU名称"
          v-model="skuFormData.skuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="价格(元)" prop="price">
        <el-input-number
          :min="0"
          controls-position="right"
          class="sku-input-number"
          v-model="skuFormData.price"
        />
      </el-form-item>
      <el-form-item label="重量(千克)" prop="weight">
        <el-input-number
          :min="0"
          controls-position="right"
          class="sku-input-number"
          v-model="skuFormData.weight"
        />
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          placeholder="请输入规格描述"
          type="textarea"
          :rows="2"
          v-model="skuFormData.skuDesc"
        ></el-input>
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row :gutter="10" class="saveSku-row">
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            v-for="(attr, index) in attrList"
            :key="attr.id"
          >
            <div class="sku-wrap">
              <span>{{ attr.attrName }}</span>
              <el-select
                class="sku-select"
                v-model="skuFormData.skuAttrValueList[index]"
              >
                <el-option
                  v-for="attrValue in attr.attrValueList"
                  :key="attrValue.id"
                  :label="attrValue.valueName"
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                ></el-option>
              </el-select>
            </div>
          </el-col>

          <!--   <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-select class="sku-select">
              <el-option label="111" value="111"></el-option>
            </el-select>
          </el-col> -->
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row :gutter="10" class="saveSku-row">
          <el-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            v-for="(saleAttr, index) in saleAttrList"
            :key="saleAttr.id"
          >
            <div class="sku-wrap">
              <span>{{ saleAttr.saleAttrName }}</span>
              <el-select
                class="sku-select"
                v-model="skuFormData.skuSaleAttrValueList[index]"
              >
                <el-option
                  v-for="salseAttrValue in saleAttr.spuSaleAttrValueList"
                  :key="salseAttrValue.id"
                  :label="salseAttrValue.saleAttrValueName"
                  :value="`${saleAttr.id}:${saleAttr.saleAttrName}:${salseAttrValue.id}:${salseAttrValue.saleAttrValueName}`"
                ></el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          :data="spuImageList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img :src="row.imgUrl" alt="row.imgName" class="savesku-img" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button
                type="success"
                size="small"
                v-if="row.isDefault === '1'"
                >默认图片</el-button
              >
              <el-button
                type="primary"
                size="small"
                v-else
                @click="setDefaultImg(row)"
                >设置默认图片</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="emit('setIsShow', 1)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "SaveSku",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import type { SaveSpuItem } from "@/api/product/modles/spuModels";
import { getAttrInfoListApi } from "@/api/product/attrs"; //获取属性列表请求
import { getSpuSaleAttrListApi, getSpuImageListApi } from "@/api/product/spu";
import { userCategoryStore } from "@/stores/category";
import type { AttrsList } from "@/api/product/modles/attrsModel";
import type { SpuSaleAttrList } from "@/api/product/modles/spuModels";
import { ElMessage } from "element-plus";
import type { FormRules, FormInstance } from "element-plus";
import { getSaveSkuInfoApi } from "@/api/product/sku";
import type {
  SaveSkuItem,
  SkuImageItem,
  SkuImageList,
} from "@/api/product/modles/skuModel";

const skuFormRef = ref<FormInstance>();
const emit = defineEmits(["setIsShow"]);
const props = defineProps<{ spu: SaveSpuItem }>();

const attrList = ref<AttrsList>([]); //属性列表
const saleAttrList = ref<SpuSaleAttrList>([]);
const spuImageList = ref<SkuImageList>([]);

const categoryStore = userCategoryStore();

// 获取属性列表
onMounted(async () => {
  const { categoty1Id, categoty2Id, categoty3Id } = categoryStore;
  attrList.value = await getAttrInfoListApi({
    category1Id: categoty1Id as number,
    category2Id: categoty2Id as number,
    categoty3Id: categoty3Id as number,
  });
});
// 获取销售属性列表
onMounted(async () => {
  saleAttrList.value = await getSpuSaleAttrListApi(props.spu.id as number);
});
// 获取图片列表
onMounted(async () => {
  const imageList = await getSpuImageListApi(props.spu.id as number);
  spuImageList.value = imageList.map((img) => {
    return {
      ...img,
      isDefault: "0",
    };
  });
});
// 定义表单数据
const skuFormData = reactive<SaveSkuItem>({
  skuName: "",
  price: 0,
  weight: 0,
  skuDesc: "",
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuImageList: [],
  skuDefaultImg: "",
});

const skuImageListValidator = (rules: any, value: any, callback: any) => {
  /*
    1. 至少选中一张图片
    2. 必须设置默认图片
    3. 设置的默认图片必须选中
  */
  if (!value.length) {
    callback(new Error("至少选择一张图片"));
  }
  if (value.some((img: SkuImageItem) => img.isDefault === "1")) {
    callback();
    return;
  }
  callback(new Error("至少选中默认图片"));
};

// 定义表单校验规则

const rules = reactive<FormRules>({
  skuName: [{ required: true, message: "请输入Sku名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入Sku价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入Sku重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入Sku描述", trigger: "blur" }],
  skuAttrValueList: [
    { required: true, message: "请选择平台属性", trigger: "change" },
  ],
  skuSaleAttrValueList: [
    { required: true, message: "请选择销售属性值", trigger: "change" },
  ],
  skuImageList: [
    { required: true, validator: skuImageListValidator, trigger: "change" },
  ],
});

// 默认图片
const setDefaultImg = (row: SkuImageItem) => {
  spuImageList.value.forEach((item: SkuImageItem) => {
    item.isDefault = "0";
  });
  row.isDefault = "1";
  skuFormData.skuDefaultImg = row.imgUrl;
  skuFormRef.value?.clearValidate(["skuImageList"]);
};

// 选择复选框时触发的函数
const handleSelectionChange = (val: SkuImageList) => {
  // 绑定复选框的
  skuFormData.skuImageList = val;
};

// 表单提交
const submitForm = () => {
  skuFormRef.value?.validate(async (valid) => {
    if (valid) {
      const { skuAttrValueList, skuSaleAttrValueList, ...res } = skuFormData;

      await getSaveSkuInfoApi({
        ...res,
        skuAttrValueList: skuFormData.skuAttrValueList
          .filter(Boolean)
          .map((attr) => {
            const [attrId, attrName, valueId, valueName] = attr.split(":");
            return {
              attrId: +attrId,
              attrName,
              valueId: +valueId,
              valueName,
            };
          }),
        skuSaleAttrValueList: skuFormData.skuSaleAttrValueList
          .filter(Boolean)
          .map((attr) => {
            const [
              saleAttrId,
              saleAttrName,
              saleAttrValueId,
              saleAttrValueName,
            ] = attr.split(":");
            return {
              saleAttrId: +saleAttrId,
              saleAttrName,
              saleAttrValueId: +saleAttrValueId,
              saleAttrValueName,
            };
          }),
        spuId: props.spu.id as number,
        category3Id: categoryStore.categoty3Id as number,
      });
      ElMessage.success("添加Sku成功");
      emit("setIsShow", 1);
    }
  });
};
</script>

<style lang="scss" scoped>
.sku-card {
  margin-top: 20px;
}

.sku-input-number {
  width: 100%;
}

.sku-select {
  margin-bottom: 10px;
}
.savesku-img {
  width: 150px;
  height: 100px;
}
.saveSku-row {
  width: 100%;
}
.sku-wrap {
  display: flex;
  justify-content: space-evenly;
}
</style>

<style>
.sku-input-number .el-input__inner {
  text-align: left;
}
</style>

<!-- skuAttrValueList: [{ attrId: 0, attrName: "", valueId: 0, valueName: "" }], -->

<!-- {
      "skuName": "string",
       "price": 0,
     "weight": "string"
     "skuDesc": "string",
     "isSale": 0,
 
  "skuAttrValueList": [
    {
      "attrId": 0,
      "attrName": "string",
      "valueId": 0,
      "valueName": "string"
    }
  ],
  "skuDefaultImg": "string",
 
  "skuImageList": [
    {
      
      "imgName": "string",
      "imgUrl": "string",
      "isDefault": "string",
    }
  ],

  "skuSaleAttrValueList": [
    {
      "saleAttrId": 0,
      "saleAttrName": "string",
      "saleAttrValueId": 0,
      "saleAttrValueName": "string",
    }
  ],
 
  
} -->
